export interface PunishTableAttr {
	// 列表数据
	data: Record<string, any>[];
	// 请求数据的loading
	loading: boolean;
	// 已勾选的数据id集合
	selectedKeys: (string | number)[];
	// 当前页
	current: number;
	// 当前页码大小
	pageSize: number;
	// 总条数
	total: number;
	// 分页选择数配置
	pageSizeOptions: string[];

	// 搜索参数对象集合
	searchObj: Record<string, any>;

	[propKey: string]: any;
}

export const usePunishTableHooks = () => {
	const apiFn = ref<any>();
	const tableAttr = reactive<PunishTableAttr>({
		data: [],
		loading: false,
		selectedKeys: [],
		current: 1,
		pageSize: 10,
		total: 0,
		pageSizeOptions: ['10', '20', '30', '50', '100'],
		searchObj: {}
	});

	const setApiFn = (api: any) => {
		apiFn.value = api;
	};

	const setTableData = async (isReset?: boolean): Promise<void> => {
		try {
			tableAttr.loading = true;
			const query = JSON.stringify(tableAttr.searchObj) !== '{}' ? JSON.parse(JSON.stringify(tableAttr.searchObj)) : {};

			const newFetchQuery = {
				current: !isReset ? tableAttr.current : 1,
				pageSize: !isReset ? tableAttr.pageSize : 10,
				...query
			};

			const resData = await apiFn.value(newFetchQuery);

			if (resData && JSON.stringify(resData) !== '{}') {
				if (Reflect.has(resData, 'total') && typeof resData.total === 'number') {
					tableAttr.total = resData.total;
				}
				if (Reflect.has(resData, 'list') && Array.isArray(resData.list)) {
					tableAttr.data = resData.list;
				}

				if (isReset) {
					tableAttr.current = newFetchQuery.current;
					tableAttr.pageSize = newFetchQuery.pageSize;
				}
			}
		} catch (error) {
			console.log('table数据获取的接口请求报错: ', error);
		} finally {
			tableAttr.loading = false;
		}
	};

	const setTablePagination = (pageIndex: number, pageSize: number): void => {
		tableAttr.current = pageIndex;
		tableAttr.pageSize = pageSize;
		setTableData();
	};

	return {
		tableAttr,
		setApiFn,
		setTableData,
		setTablePagination
	};
};
